package serie07;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Observable;
import java.util.Observer;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class Swelling {
	
	// ATTRIBUTS
	
	private static final int CENT = 100;
	
	// La fenetre principale de l'application
	private JFrame frame;
	
	// Le bouton plus
	private JButton plus;
	
	// Le bouton moins
	private JButton moins;
	
	// Le modele
	private StdSwellingModel model;
	
	// Le champ à remplir
	private JTextField textField;
	
	// CONSTRUCTEURS
	
	public Swelling() {
		createModel();
        createView();
        placeComponents();
        createController();
		model.notifyObservers();
	}
	
	// COMMANDES

    /**
     * Rend l'application visible au centre de l'�cran.
     */
    public void display() {
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
    
    // OUTILS
    
    private void createModel() {
        model = new StdSwellingModel(); 
    }
    
    protected void createView() {
    	frame = new JFrame("Baudruche");
    	plus = new JButton("plus");
    	moins = new JButton("moins");
    	textField = new JTextField(3);
    	model.addObserver(new Observer() {
            public void update(Observable o, Object arg) {
            	frame.setPreferredSize(model.getDimension());
            	frame.pack();
            	frame.setLocationRelativeTo(null);
            }
    	});
    }
    
    private void placeComponents() {
    	JPanel p = new JPanel(); {
    		p.add(plus);
    		p.add(moins);
    	}
    	frame.add(p, BorderLayout.NORTH);
    	p = new JPanel(); {
    		JLabel facteur = new JLabel("Facteur");
    		JLabel pourcentage = new JLabel("%");
    		p.add(facteur);
    		p.add(textField);
    		p.add(pourcentage);
    	}
    	frame.add(p);
    }
    
    private void createController() {
    	plus.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            	model.inflate(
            			(double) Integer.decode(textField.getText()) / CENT);
            }
    	});
    	moins.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            	model.deflate(
            			(double) Integer.decode(textField.getText()) / CENT);
            }
    	});
    	frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new Swelling().display();
            }
        });
    }

}
